package shopping;

import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;

import javax.servlet.*;
import javax.servlet.http.*;

import shopping.event.EventHandlerBase;

public class ShoppingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private Map<String, EventHandlerBase> events = new HashMap<String, EventHandlerBase>();
	
    public void init() throws ServletException {//khoi? tao. & nap cac' handlers xu ly cac event tu` client
    	
	    ResourceBundle bundle = ResourceBundle.getBundle("Event");
	    
	    Enumeration<String> e = bundle.getKeys();
	    
	    while (e.hasMoreElements()) {
		    String key = (String) e.nextElement();
		    String value = bundle.getString(key);
		    
		    try {
			    EventHandlerBase handler = (EventHandlerBase) Class.forName(value).newInstance();
			    events.put(key, handler);
		    } catch (Exception exc) {

		    }
	    }
    }
    
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

    	String event = validateEvent(request);
		EventHandlerBase handler = getEventHandler(event);
       
        String resultPage = handler.execute(request, response);
        
        dispatch(request, response, resultPage);
    }
	
    private String validateEvent (HttpServletRequest request) {
		String e = request.getParameter(Constants.EVENT);
		if (e == null || !events.containsKey(e)) {
			e = Constants.UNKNOWN_EVENT;
		}
		return e;
	}
	
    private EventHandlerBase getEventHandler (String e) {
		EventHandlerBase c;
		try {
			c = (EventHandlerBase) events.get(e);
		} catch (Exception exc) {
			c = (EventHandlerBase) events.get(Constants.UNKNOWN_EVENT);
		}
		return c;
	}
	
	private void dispatch(HttpServletRequest request, HttpServletResponse response, String url)
		throws ServletException, IOException {
		
		ServletContext sc = getServletContext();
		RequestDispatcher rd = sc.getRequestDispatcher(url);
		rd.forward(request, response);
	}
}